import { computed } from 'vue'
import { editorInfos } from '@/stores/editor'
import useSaveWork from '@/hooks/useSaveWork'
import pinia from '@/stores/index'
import { ref } from 'vue'

import { gloabl } from '@/stores/global'
import { useRoute } from 'vue-router'
import { takeScreenshotAndUpload } from '@/constant/helper'

const usePublishWork = () => {
  const globalStore = gloabl(pinia)
  const editorStore = editorInfos(pinia)
  const route = useRoute()
  const currentWorkId = route.params.id as string

  const isPublishing = ref(false)
  const { saveWork } = useSaveWork(true)
  const channels = computed(() => editorStore.channels)

  const publishWork = async (el: HTMLElement) => {
    try {
      //1 take screenshot and upload
      const resp = await takeScreenshotAndUpload(el)
      if (resp) {
        //2 update page coverImg in store
        editorStore.updatePage({ key: 'coverImg', value: resp.data.urls[0] })
        //3 save work
        await saveWork()
        //4 publish work
        await editorStore.publishWork(currentWorkId)
        //5 get channels list
        await editorStore.fetchChannels(currentWorkId)
        //6 if channels list length is 0, create a new channel
        if (channels.value.length == 0)
          await editorStore.createChannel({ name: '默认', workId: parseInt(currentWorkId) })
      }
    } catch (error) {
      console.log(error)
    } finally {
      isPublishing.value = false
    }
  }

  return { publishWork, isPublishing }
}
export default usePublishWork
